#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

# 安装编译前必要应用
function install_development() {
  sudo yum install -y autoconf-archive
  source /etc/profile
}

function download_codes(){
  echo "# 正在下载samtools与相关文件"
  wget -t 40 -c -P $1 https://github.com/samtools/samtools/releases/download/1.3.1/samtools-1.3.1.tar.bz2
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# samtools克隆成功\033[0m"
  else
    echo -e "\033[31m# samtools克隆失败,请重新执行脚本\033[0m"
    exit 1
  fi
  wget -t 40 -c -P $1 https://github.com/samtools/htslib/releases/download/1.3.1/htslib-1.3.1.tar.bz2
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# htslib克隆成功\033[0m"
  else
    echo -e "\033[31m# htslib克隆失败,请重新执行脚本\033[0m"
    exit 1
  fi
  wget -O "$1"/ax_with_htslib.m4 https://github.com/samtools/samtools/files/62424/ax_with_htslib.m4.txt
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# 依赖文件ax_with_htslib.m4下载成功\033[0m"
  else
    echo -e "\033[31m# 依赖文件ax_with_htslib.m4下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
  tar xf $1/samtools-1.3.1.tar.bz2 -C $1
  tar xf $1/htslib-1.3.1.tar.bz2 -C $1
  mv $1/samtools-1.3.1 $1/samtools
  mv $1/htslib-1.3.1 $1/htslib
  cd "$1"/samtools
  mkdir autoconf-archive
  mv ../ax_with_htslib.m4 autoconf-archive/ax_with_htslib.m4
  cd "$1"/htslib
}

function install_samtools(){
  cd "$1"/htslib
  aclocal
  autoconf
  cd "$1"/samtools
  aclocal -Iautoconf-archive
  autoconf
  ./configure CC=clang --without-curses --prefix=$2/samtools-1.3.1
  sed -i 's/$(CURSES_LIB)//g' Makefile
  make -j $(nproc) && make install
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# samtools已经安装成功\033[0m"
  else
    echo -e "\033[31m# samtools安装失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function write_samtools_module() {
  cat >"$1/samtools-1.3.1/samtools_modulefiles"<<EOF
#%Module1.0
conflict samtools
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
prepend-path PATH \$pwd/bin
EOF
}


function main() {
  is_equal_build_install_path "$1" "$2"
  install_development
  download_codes "$1"
  install_samtools "$1" "$2"
  write_samtools_module "$2"
  rm -rf "$1"/samtools
  rm -rf "$1"/htslib
}

main "$@"
